<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="160px"
      v-loading="formLoading"
    >
      <el-form-item label="合同模板名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入合同模板名称" />
      </el-form-item>
      <el-form-item label="合同类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择合同类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CONTRACT_TYPE)"
            :key="dict.value"
            :value="dict.value"
            :label="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同标识" prop="code">
        <el-input v-model="formData.code" placeholder="请输入合同标识" />
      </el-form-item>
      <el-form-item label="业务编号" prop="bizNo">
        <el-select v-model="formData.bizNo" placeholder="请选择业务编号" style="width: 100%">
          <el-option
            v-for="item in projectList"
            :key="item.projectNo"
            :label="item.projectName"
            :value="item.projectNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据源" prop="datasourceSeleted">
        <el-select multiple v-model="formData.datasourceSeleted" placeholder="选择数据源">
          <el-option
            v-for="op in dataSource"
            :label="op.name"
            :value="op.code"
            :key="op.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核人员" prop="tenantSelected" v-if="formType === 'create'">
        <el-select
          multiple
          v-model="formData.tenantSelected"
          placeholder="请选择审核人员"
          style="width: 100%"
        >
          <el-option v-for="item in tenants" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DatasourceApi, DatasourceSaveReqVO } from '@/api/contract/datasource'
import { ProjectInfo, TemplateApi, TenantInfo } from '@/api/contract/template'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  type: undefined,
  code: undefined,
  bizNo: undefined,
  tenantSelected: [],
  datasourceSeleted: [],
  datasourceCodes: undefined,
  reviewRespVOS: undefined,
  tenants: []
})
const formRules = reactive({
  name: [{ required: true, message: '合同模板名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '合同类型', trigger: 'blur' }],
  code: [{ required: true, message: '合同标识不能为空', trigger: 'blur' }],
  bizNo: [{ required: true, message: '业务编号不能为空', trigger: 'blur' }],
  tenantSelected: [{ required: true, message: '审核人员不能为空', trigger: 'blur' }],
  datasourceSeleted: [{ required: true, message: '数据源不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const projectList = ref<Array<ProjectInfo>>([])
const tenants = ref<Array<TenantInfo>>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  if (formType.value == 'create') {
    _getTenants()
  }
  resetForm()
  _getProjectList()
  getDataSource()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TemplateApi.getTemplate(id)
      if (formData.value.datasourceCodes) {
        formData.value.datasourceSeleted = formData.value.datasourceCodes.split(',')
      }
      if (formData.value.reviewRespVOS) {
        formData.value.tenants = formData.value.reviewRespVOS.map((item) => {
          return {
            tenantId: item.reviewId,
            tenantName: item.reviewName
          }
        })
      }
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    // const data = formData.value as unknown as BaseVehic=leApi.BaseVehicleVO
    // let paramsData = new FormData()
    let paramsData = {}
    const keys = Object.keys(formData.value)

    keys.forEach((key) => {
      if (formData.value[key] != undefined) {
        paramsData[key] = formData.value[key]
      }
    })

    if (formData.value.datasourceSeleted) {
      paramsData.datasourceCodes = formData.value.datasourceSeleted.join(',')
    }

    if (formType.value === 'create') {
      const tenantList = formData.value.tenantSelected.map((value) => {
        const data = tenants.value.find((item) => item.id === value) as TenantInfo
        return {
          tenantId: data.id,
          tenantName: data.name
        }
      })
      paramsData.tenants = tenantList
      await TemplateApi.create(paramsData)
      message.success(t('common.createSuccess'))
    } else {
      await TemplateApi.update(paramsData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    // close(true)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    type: undefined,
    code: undefined,
    bizNo: undefined,
    tenantSelected: [],
    datasourceSeleted: [],
    datasourceCodes: undefined,
    reviewRespVOS: undefined,
    tenants: []
  }
  formRef.value?.resetFields()
}

const _getProjectList = async () => {
  const data = await TemplateApi.getProjectList({})
  projectList.value = data as Array<ProjectInfo>
}

const _getTenants = async () => {
  const data = await TemplateApi.getTenants({})
  tenants.value = data as Array<TenantInfo>
}
const dataSource = ref<Array<DatasourceSaveReqVO>>([]) // 模板数据源
// 获取模板关联的数据源
const getDataSource = async () => {
  const { list } = await DatasourceApi.getPage({})
  dataSource.value = list
}
</script>
<style rel="stylesheet/scss" lang="scss">
.disabled .el-upload--picture-card {
  display: none;
}
</style>
